package com.xyf.sys.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyf.sys.domain.*;
import com.xyf.sys.mapper.*;
import com.xyf.sys.service.ILogisticService;
import com.xyf.sys.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author R-H
 * @Date 2024/1/281703
 * @Description
 */
@RestController
@RequestMapping
@Slf4j
public class DataSyncController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private UserPrinterMapper userPrinterMapper;
    @Autowired
    private UserLogisticMapper logisticMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private ILogisticService logisticService;
    String regex = "[\u4e00-\u9fa5]+";
    Pattern pattern = Pattern.compile(regex);

    @Autowired
    private ResourceLoader resourceLoader;
    private ExecutorService executorService = new ThreadPoolExecutor(
            1, // 核心线程数
            2, // 最大线程数
            60L, // 空闲线程等待新任务的最长时间
            TimeUnit.SECONDS,
            new java.util.concurrent.ArrayBlockingQueue<>(100) // 任务队列
    );
    ;

    @PostMapping("/sync/{lineNo}")
    public Object sync(@PathVariable Integer lineNo) throws IOException {
        String file = "database-orders.json";
        Resource resource = resourceLoader.getResource("classpath:" + file);
        File file1 = resource.getFile();
        //212643
        executorService.submit(() -> syncData(lineNo, file1));
        return "OK";
    }

    @PostMapping("/addressSync")
    public Object addressSync(@PathVariable Integer lineNo) throws IOException {
        String file = "database-orders.json";
        Resource resource = resourceLoader.getResource("classpath:" + file);
        File file1 = resource.getFile();
        executorService.submit(() -> addressSync(file1));
        return "OK";
    }

    private void addressSync(File file) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(line);
                    UserAddress address = new UserAddress();
                    address.setUserId(jsonObject.getString("OPENID_self"));
                    address.setName(jsonObject.getString("name"));
                    address.setMobile(jsonObject.getString("mobile"));
                    address.setCompany(jsonObject.getString("company"));
                    address.setProvince(jsonObject.getString("province"));
                    address.setCity(jsonObject.getString("city"));
                    address.setArea(jsonObject.getString("area"));
                    address.setTown(jsonObject.getString("town"));
                    address.setAddress(jsonObject.getString("address"));
                    address.setCode(jsonObject.getString("code"));
                    if ("收件地址".equals(jsonObject.getString("address_type"))) {
                        address.setType(2);
                    }
                    if ("寄件地址".equals(jsonObject.getString("address_type"))) {
                        address.setType(1);
                    }
                    address.setStatus("0");
                    if (jsonObject.getLong("timestamp_update") != null) {
                        address.setLastUpdateTime(new Date(jsonObject.getLong("timestamp_update")));
                    }
                    address.setRemark(jsonObject.getString("from"));
                    address.setIsDefault(0);
                    address.setDelFlag("0");
                    userAddressMapper.insert(address);
                } catch (Exception e) {

                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void syncData(Integer lineNo, File file) {
        String line = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            Integer i = 1;
            while ((line = br.readLine()) != null) {
                try {
                    i++;
                    if (i <= lineNo) {
                        continue;
                    }
                    System.out.println(line);
                    JSONObject jsonObject = JSONObject.parseObject(line);
                    Order order = new Order();
                    order.setId(jsonObject.getString("_id"));
                    order.setProductCategory(1);
                    order.setOutTradeNo(jsonObject.getString("outTradeNo"));
                    order.setAppid(jsonObject.getString("from_appid"));
                    order.setUserId(jsonObject.getString("OPENID_self"));
                    order.setRegimentId(jsonObject.getString("OPENID_regiment"));
                    User user = userMapper.selectByPrimaryKey(order.getUserId());
                    if (user != null) {
                        order.setMobile(user.getMobile());
                    }
                    if (jsonObject.getLong("timestamp_init") != null) {
                        order.setOrderTime(new Date(jsonObject.getLong("timestamp_init")));
                    }
                    if (jsonObject.getLong("timestamp_pay_callback") != null) {
                        order.setCallbackTime(new Date(jsonObject.getLong("timestamp_pay_callback")));
                    }
                    order.setTransactionId(jsonObject.getString("transaction_id"));
                    order.setPayStatus(jsonObject.getInteger("payStatus"));
                    order.setPrintTimes(jsonObject.getInteger("x_print_times"));
                    if (jsonObject.getLong("timestamp_init") != null) {
                        order.setOrderTime(new Date(jsonObject.getLong("timestamp_init")));
                    }
                    if (jsonObject.getLong("timestamp_update") != null) {
                        order.setLastUpdateTime(new Date(jsonObject.getLong("timestamp_update")));
                    }
                    String totalFee = jsonObject.getString("totalFee");
                    order.setCreateTime(new Date());
                    order.setDelFlag("0");
                    if (StringUtils.isNotBlank(totalFee)) {
                        try {
                            BigDecimal decimal = new BigDecimal(totalFee);
                            order.setTotalPrice(decimal);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    orderMapper.insert(order);
                    JSONArray products = jsonObject.getJSONArray("products");
                    if (products != null) {
                        for (int s = 0; s < products.size(); s++) {
                            JSONObject jsonObject1 = products.getJSONObject(s);
                            OrderProduct product = new OrderProduct();
                            product.setId(jsonObject1.getString("_id"));
//                        product.setProductCategory();
                            product.setBizId(jsonObject1.getString("biz_id"));
                            product.setDeliveryName(jsonObject1.getString("deliveryName"));
                            product.setDeliveryId(jsonObject1.getString("deliveryId"));
                            product.setWaybillId(jsonObject1.getString("waybillId"));
                            JSONArray waybillData = jsonObject1.getJSONArray("waybillData");
                            JSONArray d = new JSONArray();
                            if (waybillData != null && waybillData.size() > 0) {
                                for (int i1 = 0; i1 < waybillData.size(); i1++) {
                                    JSONObject jsonObject2 = waybillData.getJSONObject(i1);
                                    String value = jsonObject2.getString("value");
                                    Matcher matcher = pattern.matcher(value);
                                    JSONObject jsonObject3 = new JSONObject();
                                    if (matcher.find()) {
                                        jsonObject3.put("packagePlace", value);
                                        product.setPackagePlace(value);
                                    } else {
                                        jsonObject3.put("bigWord", value);
                                        product.setBigWord(value);
                                    }
                                    d.add(jsonObject3);
                                }
                                product.setWaybillData(d.toJSONString());
                            }
                            product.setItemType(jsonObject1.getString("itemType"));
                            product.setItemNotes(jsonObject1.getString("itemNotes"));
                            product.setWeight(jsonObject1.getString("weight"));
                            product.setPickUpType(jsonObject1.getString("pickUpType"));
                            product.setTotalPrice(order.getTotalPrice());
                            product.setDescribe(jsonObject1.getString("describe"));
                            if (jsonObject1.getString("totalFee_pickup") != null) {
                                product.setPickUpPrice(new BigDecimal(jsonObject1.getString("totalFee_pickup")));
                            }
                            product.setOrderId(order.getId());
                            product.setUserId(order.getUserId());
                            product.setCreateTime(new Date());
                            product.setDelFlag("0");
                            product.setStatus("0");
                            JSONObject recMan = jsonObject1.getJSONObject("recMan");
                            if (recMan != null) {
                                OrderAddress orderAddress = new OrderAddress();
                                orderAddress.setOrderProductId(product.getId());
                                orderAddress.setName(recMan.getString("name"));
                                orderAddress.setMobile(recMan.getString("mobile"));
                                orderAddress.setOrderId(order.getId());
                                orderAddress.setUserId(order.getUserId());
                                orderAddress.setCountry(recMan.getString("country"));
                                orderAddress.setProvince(recMan.getString("province"));
                                orderAddress.setCity(recMan.getString("city"));
                                orderAddress.setArea(recMan.getString("area"));
                                orderAddress.setTown(recMan.getString("town"));
                                orderAddress.setAddress(recMan.getString("address"));
                                orderAddress.setCode(recMan.getString("code"));
                                orderAddress.setCountry(recMan.getString("country"));
                                orderAddress.setCompany(recMan.getString("company"));
                                orderAddress.setSource(recMan.getString("from"));
                                orderAddress.setType(2);
                                orderAddress.setCreateTime(new Date());
                                orderAddress.setDelFlag("0");
                                orderAddress.setStatus("0");
                                orderAddressMapper.insert(orderAddress);
                            }
                            JSONObject sendMan = jsonObject1.getJSONObject("sendMan");
                            if (sendMan != null) {
                                OrderAddress orderAddress = new OrderAddress();
                                orderAddress.setOrderProductId(product.getId());
                                orderAddress.setName(sendMan.getString("name"));
                                orderAddress.setMobile(sendMan.getString("mobile"));
                                orderAddress.setOrderId(order.getId());
                                orderAddress.setUserId(order.getUserId());
                                orderAddress.setCountry(sendMan.getString("country"));
                                orderAddress.setProvince(sendMan.getString("province"));
                                orderAddress.setCity(sendMan.getString("city"));
                                orderAddress.setArea(sendMan.getString("area"));
                                orderAddress.setTown(recMan.getString("town"));
                                orderAddress.setAddress(sendMan.getString("address"));
                                orderAddress.setCode(sendMan.getString("code"));
                                orderAddress.setCountry(sendMan.getString("country"));
                                orderAddress.setCompany(sendMan.getString("company"));
                                orderAddress.setSource(sendMan.getString("from"));
                                orderAddress.setType(1);
                                orderAddress.setCreateTime(new Date());
                                orderAddress.setDelFlag("0");
                                orderAddress.setStatus("0");
                                orderAddressMapper.insert(orderAddress);
                            }
                            orderProductMapper.insert(product);
                        }
                    }
                } catch (Exception e) {

                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/test")
    public Object test() {
        String file = "E:\\需求\\导出\\database_export-prod-6g79769jb69fe325-users.json";
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        String line = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                JSONObject jsonObject = JSONObject.parseObject(line);
                JSONObject info_self = jsonObject.getJSONObject("info_self");
                JSONObject location = jsonObject.getJSONObject("location");
                User user = new User();
                user.setId(jsonObject.getString("OPENID"));
                user.setOpenid(jsonObject.getString("OPENID"));
                user.setUnionid(jsonObject.getString("UNIONID"));
                if (info_self != null) {
                    user.setName(info_self.getString("name"));
                    user.setMobile(info_self.getString("mobile"));
                    user.setAvatar(info_self.getString("avatar"));
                    user.setCountry(info_self.getString("country"));
                    user.setProvince(info_self.getString("province"));
                    user.setCity(info_self.getString("city"));
                    user.setArea(info_self.getString("area"));
                    user.setAddress(info_self.getString("address"));
                    user.setCode(info_self.getString("code"));
                }
                user.setLocationName(jsonObject.getString("location_name"));
                if (location != null) {
                    JSONArray coordinates = location.getJSONArray("coordinates");
                    for (int i = 0; i < coordinates.size(); i++) {
                        BigDecimal bigDecimal = coordinates.getBigDecimal(i);
                        if (i == 0) {
                            user.setLongitude(bigDecimal);
                        }
                        if (i == 1) {
                            user.setLatitude(bigDecimal);
                        }
                    }
                }
                user.setParentId(jsonObject.getString("OPENID_agent"));
                user.setRegimentId(jsonObject.getString("OPENID_regiment"));
                user.setCreateTime(new Date(jsonObject.getLong("timestamp_update")));
                userMapper.insert(user);
                JSONObject address_info = jsonObject.getJSONObject("address_info");
                if (address_info != null) {
                    UserAddress address = new UserAddress();
                    address.setUserId(user.getId());
                    address.setName(address_info.getString("name"));
                    address.setMobile(address_info.getString("mobile"));
                    address.setCompany(address_info.getString("company"));
                    address.setProvince(address_info.getString("province"));
                    address.setCity(address_info.getString("city"));
                    address.setArea(address_info.getString("area"));
                    address.setAddress(address_info.getString("address"));
                    address.setCode(address_info.getString("code"));
                    if ("寄件地址".equalsIgnoreCase(address_info.getString("address_type"))) {
                        address.setType(2);
                    } else {
                        address.setType(1);
                    }
                    address.setCode(address_info.getString("code"));
                    address.setCreateTime(new Date());
                    address.setStatus("0");
                    address.setDelFlag("0");
                    userAddressMapper.insert(address);
                    JSONArray logistics = jsonObject.getJSONArray("logistics");
                    if (logistics != null) {
                        for (int i = 0; i < logistics.size(); i++) {
                            JSONObject jsonObject1 = logistics.getJSONObject(i);
                            UserLogistic logistic = new UserLogistic();
                            logistic.setUserId(user.getId());
                            logistic.setBizId(jsonObject1.getString("bizId"));
                            logistic.setDeliveryName(jsonObject1.getString("deliveryName"));
                            logistic.setDeliveryId(jsonObject1.getString("deliveryId"));
                            logistic.setPassword(jsonObject1.getString("password"));
                            logistic.setType(jsonObject1.getString("type"));
                            logistic.setCreateTime(new Date());
                            logistic.setDelFlag("0");
                            logistic.setStatus("0");
                            logisticMapper.insert(logistic);
                        }
                    }
                }
                JSONArray printers = jsonObject.getJSONArray("printers");
                if (printers != null) {
                    for (int i = 0; i < printers.size(); i++) {
                        JSONObject jsonObject1 = printers.getJSONObject(i);
                        UserPrinter printer = new UserPrinter();
                        printer.setUserId(user.getId());
                        printer.setDirection(jsonObject1.getString("direction"));
                        printer.setSiid(jsonObject1.getString("siid"));
                        printer.setCreateTime(new Date());
                        printer.setDelFlag("0");
                        printer.setStatus("0");
                        userPrinterMapper.insert(printer);
                    }
                }
                JSONArray roles = jsonObject.getJSONArray("roles");
                if (roles != null) {
                    for (int i = 0; i < roles.size(); i++) {
                        Integer integer = roles.getInteger(i);
                        Role role = null;
                        if (integer == null) {
                            continue;
                        }
                        if (integer == 0) {
                            role = roleMapper.selectByRoleKey("DEVELOP");
                        }
                        if (integer == 2) {
                            role = roleMapper.selectByRoleKey("REGIMENT");
                        }
                        if (integer == 3) {
                            role = roleMapper.selectByRoleKey("REGIMENT");
                        }
                        if (integer == 7) {
                            role = roleMapper.selectByRoleKey("REGIMENT");
                        }
                        if (integer == 701) {
                            role = roleMapper.selectByRoleKey("701");
                        }
                        if (integer == 201 || integer == 3001) {
                            role = roleMapper.selectByRoleKey("3001");
                        }
                        if (role != null) {
                            UserRole userRole = new UserRole();
                            userRole.setUserId(user.getOpenid());
                            userRole.setRoleId(role.getId());
                            UserRole userRole1 = userRoleMapper.select(user.getOpenid(), role.getId());
                            if (userRole1 == null) {
                                userRoleMapper.insert(userRole);
                            }
                        }
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @PostMapping("/queryRoute")
    public Object queryRoute(@RequestParam String a, @RequestParam String b) {
        return R.ok(logisticService.queryRoute(a, b));
    }

    @PostMapping("/test2")
    public Object test2() {
        String file = "F:\\207\\a\\database_export-prod-6g79769jb69fe325-orders.json";
        String line = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                JSONObject jsonObject = JSONObject.parseObject(line);
                Order order = new Order();
                order.setId(jsonObject.getString("_id"));
//                order.setProductCategory(jsonObject.getInteger("product_category"));
                order.setOutTradeNo(jsonObject.getString("outTradeNo"));
                order.setUserId(jsonObject.getString("OPENID_self"));
                order.setRegimentId(jsonObject.getString("OPENID_regiment"));
                order.setPayStatus(jsonObject.getInteger("payStatus"));
                order.setPrintTimes(jsonObject.getInteger("x_print_times"));
                if (jsonObject.getLong("timestamp_init") != null) {
                    order.setOrderTime(new Date(jsonObject.getLong("timestamp_init")));
                }
                if (jsonObject.getLong("timestamp_update") != null) {
                    order.setUpdateTime(new Date(jsonObject.getLong("timestamp_update")));
                }
                if (jsonObject.getLong("timestamp_pay_callback") != null) {
                    order.setCallbackTime(new Date());
                }
                String totalFee = jsonObject.getString("totalFee");
                order.setCreateTime(new Date());
                order.setDelFlag("0");
                if (StringUtils.isNotBlank(totalFee)) {
                    try {
                        BigDecimal decimal = new BigDecimal(totalFee);
                        order.setTotalPrice(decimal);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                orderMapper.insert(order);
                JSONArray products = jsonObject.getJSONArray("products");
                if (products != null) {
                    for (int i = 0; i < products.size(); i++) {
                        JSONObject jsonObject1 = products.getJSONObject(i);
                        OrderProduct product = new OrderProduct();
                        product.setId(jsonObject1.getString("_id"));
                        product.setProductCategory(jsonObject1.getString("product_category"));
                        product.setBizId(jsonObject1.getString("biz_id"));
                        product.setDeliveryName(jsonObject1.getString("deliveryName"));
                        product.setDeliveryId(jsonObject1.getString("deliveryId"));
                        product.setWaybillId(jsonObject1.getString("waybillId"));
                        product.setWaybillData(jsonObject1.getString("waybillData"));
                        product.setItemType(jsonObject1.getString("itemType"));
                        product.setItemNotes(jsonObject1.getString("itemNotes"));
                        product.setWeight(jsonObject1.getString("weight"));
                        product.setPickUpType(jsonObject1.getString("pickUpType"));
                        product.setOrderId(order.getId());
                        product.setUserId(order.getUserId());
                        product.setCreateTime(new Date());
                        product.setDelFlag("0");
                        product.setStatus("0");
                        JSONObject recMan = jsonObject1.getJSONObject("recMan");
                        if (recMan != null) {
                            OrderAddress orderAddress = new OrderAddress();
                            orderAddress.setOrderProductId(product.getId());
                            orderAddress.setName(recMan.getString("name"));
                            orderAddress.setMobile(recMan.getString("mobile"));
                            orderAddress.setOrderId(order.getId());
                            orderAddress.setUserId(order.getUserId());
                            orderAddress.setCountry(recMan.getString("country"));
                            orderAddress.setProvince(recMan.getString("province"));
                            orderAddress.setCity(recMan.getString("city"));
                            orderAddress.setArea(recMan.getString("area"));
                            orderAddress.setTown(recMan.getString("town"));
                            orderAddress.setAddress(recMan.getString("address"));
                            orderAddress.setCode(recMan.getString("code"));
                            orderAddress.setCountry(recMan.getString("country"));
                            orderAddress.setCompany(recMan.getString("company"));
                            orderAddress.setSource(recMan.getString("from"));
                            orderAddress.setType(2);
                            orderAddress.setCreateTime(new Date());
                            orderAddress.setDelFlag("0");
                            orderAddress.setStatus("0");
                            orderAddressMapper.insert(orderAddress);
                        }
                        JSONObject sendMan = jsonObject1.getJSONObject("sendMan");
                        if (sendMan != null) {
                            OrderAddress orderAddress = new OrderAddress();
                            orderAddress.setOrderProductId(product.getId());
                            orderAddress.setName(sendMan.getString("name"));
                            orderAddress.setMobile(sendMan.getString("mobile"));
                            orderAddress.setOrderId(order.getId());
                            orderAddress.setUserId(order.getUserId());
                            orderAddress.setCountry(sendMan.getString("country"));
                            orderAddress.setProvince(sendMan.getString("province"));
                            orderAddress.setCity(sendMan.getString("city"));
                            orderAddress.setArea(sendMan.getString("area"));
                            orderAddress.setTown(recMan.getString("town"));
                            orderAddress.setAddress(sendMan.getString("address"));
                            orderAddress.setCode(sendMan.getString("code"));
                            orderAddress.setCountry(sendMan.getString("country"));
                            orderAddress.setCompany(sendMan.getString("company"));
                            orderAddress.setSource(sendMan.getString("from"));
                            orderAddress.setType(1);
                            orderAddress.setCreateTime(new Date());
                            orderAddress.setDelFlag("0");
                            orderAddress.setStatus("0");
                            orderAddressMapper.insert(orderAddress);
                        }
                        orderProductMapper.insert(product);
                    }
                }
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
